<template>
  <view class="ui-field" :class="[error ? 'is-error': '']">
    <uiCell
      :title="label"
      :titleWidth="labelWidthItem"
      customclass="field-cell"
      uicellLeftClass="field-cell--left"
      uiCellRightClass="field-cell--right"
    >
      <slot name="title" slot="title" v-if="$slots.title" />
      <template slot="value">
        <view class="field-body">
          <slot name="input" v-if="$slots.input"></slot>
          <template v-else>
            <textarea
              v-if="type === 'textarea'"
              class="ui-field--control"
              :class="[disabled ? 'is-disabled' : '' , `is-${inputAlignItem}`]"
              :disabled="disabled || readonly"
              :value="value"
              :placeholder="placeholder"
              :placeholder-class="'ui-field--control-placeholder'"
              :maxlength="maxlength"
              :fixed="fixed"
              :auto-height="autosize"
            ></textarea>
            <input
              ref="input"
              v-else
              class="ui-field--control"
              :type="type"
              :class="[disabled ? 'is-disabled' : '' , `is-${inputAlignItem}`]"
              :disabled="disabled || readonly"
              :value="value"
              :placeholder="placeholder"
              :placeholder-class="'ui-field--control-placeholder'"
              :maxlength="maxlength"
              :password="type === 'password'"
              @blur="onBlur"
              @input="onInput"
              @focus="onFocus"
            />
          </template>

          <!-- 如果插入按钮 -->
          <view class="ui-field--button">
            <slot name="button" />
          </view>
        </view>
        <view
          v-if="errorMessage || validateMessage"
          class="ui-field--error-message"
          :class="[`is-${errorMessageAlign}`]"
        >{{ errorMessage || validateMessage }}</view>
      </template>
    </uiCell>
  </view>
</template>

<script>
import uiCell from "components/base/cell/index";

import { fieldMixins } from "@/components/utils/validate.js";
import { isDef } from "@/utils/validate/data.js";

export default {
  name: "uiField",
  components: {
    uiCell
  },
  mixins: [fieldMixins],
  inject: ["uiform"],
  "mp-weixin": {
    options: {
      styleIsolation: "shared"
    }
  },
  props: {
    value: [String, Number],
    // field的类型  暂时支持 text textarea password , number , idcard , digit
    type: {
      type: String,
      default: "text"
    },
    size: String,
    icon: String,
    label: String,

    fixed: Boolean,
    focus: Boolean,
    center: Boolean,
    isLink: Boolean,
    leftIcon: String,
    rightIcon: String,
    disabled: Boolean,
    autosize: Boolean,
    readonly: Boolean,
    required: Boolean,
    password: Boolean,
    iconClass: String,
    clearable: Boolean,
    clickable: Boolean,
    // 输入框内容对齐方式，可选值为 center right
    inputAlign: {
      type: String
    },
    placeholder: String,
    customStyle: String,
    confirmType: String,
    confirmHold: Boolean,

    arrowDirection: String,
    placeholderStyle: String,
    rules: Array,
    // 是否是错误
    error: Boolean,
    // 错误的提示信息
    errorMessage: String,
    // 错误信息对齐方式，可选值为 center right
    errorMessageAlign: {
      type: String,
      default: "left"
    },

    selectionEnd: {
      type: Number,
      default: -1
    },
    selectionStart: {
      type: Number,
      default: -1
    },
    showConfirmBar: {
      type: Boolean,
      default: true
    },
    adjustPosition: {
      type: Boolean,
      default: true
    },
    cursorSpacing: {
      type: Number,
      default: 50
    },
    maxlength: {
      type: Number,
      default: -1
    },

    border: {
      type: Boolean,
      default: true
    },
    labelWidth: {
      type: String
    }
  },
  data() {
    return {
      validateMessage: ""
    };
  },
  computed: {
    formValue: {
      get() {
        return this.value;
      },
      set() {
        this.$emit("input", this.value);
      }
    },
    inputAlignItem() {
      return (
        this.inputAlign || (this.uiform && this.uiform.inputAlign) || "left"
      );
    },
    labelWidthItem() {
      return (
        this.inpulabelWidthtAlign ||
        (this.uiform && this.uiform.labelWidth) ||
        "180rpx"
      );
    }
  },

  watch: {
    value() {
      this.resetValidation();
      this.validateWithTrigger("onChange");
    }
  },
  created() {
    if (this.uiform) {
      this.uiform.fields.push({
        validate: this.validate
      });
    }
  },
  beforeDestroy() {
    if (this.uiform) {
      this.uiform.fields = this.uiform.fields.filter(item => item !== this);
    }
  },
  mounted() {},
  methods: {
    /**
     * 输入框内容的格式化处理
     */
    format(target = this.$refs.input) {
      if (!target) {
        return;
      }

      let { value } = target;
      const { maxlength } = this;

      // native maxlength not work when type is number
      if (!isDef(maxlength) && maxlength !== -1 && value.length > maxlength) {
        value = value.slice(0, maxlength);
        target.value = value;
      }

      // if (this.type === "number" || this.type === "digit") {
      //   const originValue = value;
      //   const allowDot = this.type === "number";

      //   value = formatNumber(value, allowDot);

      //   if (value !== originValue) {
      //     target.value = value;
      //   }
      // }

      if (this.formatter) {
        const originValue = value;
        value = this.formatter(value);

        if (value !== originValue) {
          target.value = value;
        }
      }
      this.$emit("input", value);
      return value;
    },

    onInput(event) {
      // not update v-model when composing
      if (event.target.composing) {
        return;
      }
      this.$emit("input", this.format(event.target));
    },

    onFocus(event) {
      this.focused = true;
      this.$emit("focus", event);

      // hack for safari
      /* istanbul ignore if */
      if (this.readonly) {
        this.blur();
      }
    },
    onBlur(event) {
      this.focused = false;
      this.$emit("blur", event);
      // 如果失去焦点，那么就
      // this.resetValidation();
      this.validateWithTrigger("onBlur");
      // resetScroll();
    }
  }
};
</script>

<style lang="scss" scoped>
.ui-field {
  /deep/ .field-cell {
    .ui-cell-box {
      height: 100%;
      min-height: 64rpx;
      align-items: flex-start;
    }

    .field-cell--left {
      flex: none;
      box-sizing: border-box;
      align-items: flex-start;
      height: 100%;
    }
    .field-cell--right {
      overflow: visible;
    }
  }

  &.is-error {
    &::before {
      position: absolute;
      left: 8px;
      color: #ee0a24;
      font-size: 14px;
      content: "*";
    }
    .ui-field--control {
      color: $brand-danger;
    }

    // 修改默认的输入框字体颜色背景色
    /deep/ .ui-field--control-placeholder {
      color: $brand-danger;
    }
  }

  .ui-field--control {
    display: block;
    box-sizing: border-box;
    width: 100%;
    min-width: 0;
    margin: 0;
    padding: 0;
    color: #323233;
    line-height: inherit;
    text-align: left;
    background-color: transparent;
    border: 0;
    resize: none;
    outline: none;
    min-height: 64rpx;

    &.is-disabled {
      color: #969799;
      background-color: transparent;
      cursor: not-allowed;
      opacity: 1;
      -webkit-text-fill-color: currentColor;
    }

    &.is-center {
      text-align: center;
    }
    &.is-right {
      text-align: right;
    }
  }

  .field-body {
    display: flex;
    align-items: center;
  }
  // 修改默认的输入框字体颜色背景色
  /deep/ .ui-field--control-placeholder {
    color: $color-text-placeholder;
  }
  // 插入按钮
  .ui-field--button {
    display: inline-block;
    padding-left: 30rpx;
    flex-shrink: 0;
  }
  .ui-field--error-message {
    flex-flow: column;
    color: #ee0a24;
    font-size: 12px;
    text-align: left;
    // 错误提示对齐
    &.is-center {
      text-align: center;
    }
    &.is-right {
      text-align: right;
    }
  }
}
</style>
